package com.hna.eking.AirlineServer.security;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hna.eking.AirlineServer.Utils.ResponseSupport;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;


@Controller
public class LoginController {
	
	private ObjectMapper mapper = new ObjectMapper();
//	@RequestMapping("/login/success")
//	public @ResponseBody ResponseSupport<String> loginSuccess(HttpServletRequest request) {
//		ResponseSupport<String> responseSupport = new ResponseSupport<String>();
//		responseSupport.setCode(200);
//		responseSupport.setMessage("login success");
//		return responseSupport;
//	}
	
	@RequestMapping("/login/islegaltoken")
	public @ResponseBody ResponseSupport<String> islegalToken(HttpServletRequest request) {
		ResponseSupport<String> responseSupport = new ResponseSupport<String>();
		responseSupport.setCode(201);
		String token = request.getHeader("Authorization");  
        if (token != null) {  
        	//因为BasicAuthenticationFilter已经验证过了，所以这里直接返回成功
        	responseSupport.setCode(200);
        	responseSupport.setMessage("token is legal");
//        	try {
//        		Jwts.parser().setSigningKey("MyJwtSecret").parseClaimsJws(token.replace("Bearer ", "")).getBody();
//        		responseSupport.setCode(200);
//        		responseSupport.setMessage("token is legal");
//        	} catch (JwtException e) {
//        		
//        		if(e instanceof ExpiredJwtException) {
//        			responseSupport.setMessage("token Expired");
//        		}
//        		responseSupport.setMessage("token is illegal");
//			}
        } else {
        	responseSupport.setMessage("token is null");
        }
		
		return responseSupport;
	}
	
	
	@RequestMapping("/login/failure")
	public @ResponseBody ResponseSupport<String> loginFailure(HttpServletRequest request) {
		ResponseSupport<String> responseSupport = new ResponseSupport<String>();
		responseSupport.setCode(201);
		try {
			AuthenticationException loginExcption = (AuthenticationException) request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
			responseSupport.setMessage(loginExcption.getMessage());
		} catch (Exception e) {
			responseSupport.setMessage("login failure");
		}
		
		return responseSupport;
	}
	
	@RequestMapping("/login/illegalToken")
	public ResponseEntity<Map<String,String>> illegalToken(HttpServletRequest request) {
		Map<String,String> body = new HashMap<String, String>();
		try {
			AuthenticationException loginExcption = (AuthenticationException) request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
			body.put("message", loginExcption.getMessage());
		} catch (Exception e) {
			body.put("message", "token is illegal");
		}
		return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
	}
	
	@RequestMapping("/accessDenied")
	public ResponseEntity<Map<String,String>> accessDenied(HttpServletRequest request) {
		Map<String,String> body = new HashMap<String, String>();
		body.put("message", "正在访问被保护的资源！权限不够!");
		return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body);
	}
	
	@RequestMapping("/needlogin")
	public  ResponseEntity<Map<String,String>> needLogin(HttpServletRequest request) {
		Map<String,String> body = new HashMap<String, String>();
		body.put("message", "正在访问被保护的资源！未登录!");
		return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
	}
	
	@RequestMapping("/sessionExpired")
	public ResponseEntity<String> sessionExpired(HttpServletRequest request) {
		String message = "{\"message\":\"sessionExpired\"}";
		return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(message);
	}
	
	@RequestMapping("/logout")
	public @ResponseBody ResponseSupport<String> logout(HttpServletRequest request,
			HttpServletResponse response) {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		ResponseSupport<String> responseSupport = new ResponseSupport<String>();
		if (auth != null){    
			new SecurityContextLogoutHandler().logout(request, response, auth);
			
			responseSupport.setCode(200);
			responseSupport.setMessage("logout success");
			return responseSupport;
		}
		responseSupport.setCode(201);
		responseSupport.setMessage("没有登录");
		return responseSupport;
	}
}
